import { BadRequestException, Injectable } from '@nestjs/common';
import { CreateUserDto } from './dto/login.dto';

import { Repository } from 'typeorm';
import { InjectRepository } from '@nestjs/typeorm';
import { User } from 'src/entities/user/user.entity';
import { BusinessException } from 'src/common/exceptions/business.exception.filter';
import * as bcrypt from 'bcryptjs'
import { JwtService } from "@nestjs/jwt"
import { RedisService } from 'src/db/redis/redis.service';


@Injectable()
export class UserService {
    constructor(
        private jwtService: JwtService,
        @InjectRepository(User)
        private readonly userRepository: Repository<User>,
        private redisService: RedisService,

    ) {
    }

    // 登录接口
    async toLogin(data) {
        const { name, password, code } = data
        if (!name || !password || !code) {
            throw new BusinessException({ code: 400, message: "参数错误" })
        }
        try {
            // 查询用户
            const findUser = await this.userRepository.findOne({ where: { name: name } });
            if (!findUser) return new BadRequestException('用户不存在')

            // 密码验证
            const comparaRes: boolean = bcrypt.compareSync(password, findUser.password)
            if (!comparaRes) return new BadRequestException('密码错误')

            // 生成token
            const payload = { name: findUser.name, phone: findUser.phone, user_id: findUser.user_id, date: new Date() }
            const token = this.jwtService.sign(payload)

            await this.redisService.set(
                `${findUser.user_id}&${findUser.phone}&${findUser.name}`,
                token,
                (4 * 36000))

            return { msg: '登陆成功', access_token: token }


        } catch (error) {
            throw new BusinessException(error)
        }
    }




    // 用户注册
    async register(data) {
        const { name, phone } = data
        try {
            const existUser = await this.userRepository.findOne({ where: [{ name: name }, { phone: phone }] })
            if (existUser) {
                throw new BusinessException({ code: 400, message: "用户名或手机号已存在" })
            }
            const newUser = await this.userRepository.create(data)
            await this.userRepository.save(newUser)
            return await this.userRepository.findOne({ where: { name, phone } })
        } catch (error) {
            throw new BusinessException(error)
        }

    }
    async getUser(data) {
        const { name, phone, user_id } = data
        try {
            const findUser = await this.userRepository.findOne({ where: { name: name, phone: phone } })
            return findUser
        } catch (error) {
            throw new BusinessException(error)
        }

    }
}
